<?php
  namespace app\admin\controller;
  class Home extends \think\Controller{
  	public $mec;
  	function __construct(){
  		parent::__construct();
      $this->mec=new \app\admin\controller\Memcache();
  	}
  	 function index(){
  
  	 	if(!$list=$this->mec->mem->get('fl')){
            $list=\think\Db::name('fl')->select();

            $list=$this->getChild($list);
            $this->mec->mem->set('fl',$list);
  	 	}
  	 	$this->assign('list',$list);
  	 	return $this->fetch('index/home');
  	 }

function mem(){
	        $list=\think\Db::name('fl')->select();
            $list=$this->getChild($list);
            $this->mec->mem->set('fl',$list);
}

function fl_add(){
	if(input('get.id')){
		$row=\think\Db::name('fl')->find(input('get.id'));
		$this->assign('row',$row);
	}
	if(!$list=$this->mec->mem->get('fl')){
            $list=\think\Db::name('fl')->select();

            $list=$this->getChild($list);
            $this->mec->mem->set('fl',$list);
  	 	}
  	 	$this->assign('list',$list);
	return $this->fetch('index/fl_add');
}

function fl_save(){
	$res=\think\Db::name('fl')->insert(input('post.'));
	if($res){
		$this->mem();
		echo JSON_encode(['status'=>'ok']);
	}else{
		echo JSON_encode(['status'=>'fail']);
	}
}


function fl_edit(){
	 $res=\think\Db::name('fl')->where('id',input('get.id'))->update(input('post.'));
	if($res){
		$this->mem();
		echo JSON_encode(['status'=>'ok']);
	}else{
		echo JSON_encode(['status'=>'fail']);
	}
}
function fl_delt(){
	 $res=\think\Db::name('fl')->delete(input('post.id'));
	if($res){
		$this->mem();
		echo JSON_encode(['status'=>'ok']);
	}else{
		echo JSON_encode(['status'=>'fail']);
	}
}

function getChild($data,$parent_id = 0,$level = 0){
    //声明静态数组,避免递归调用时,多次声明导致数组覆盖
    static  $result;
    foreach ($data as $key => $info){
        //第一次遍历,找到父节点为根节点的节点 也就是parent_id=0的节点
        if($info['fl_cid'] == $parent_id){
            $info['level'] = $level;
            if($info['level']!=0){
            	$str="";
            	for($i=1;$i<=$info['level'];$i++){
                 $str.="-";
            	}
            	$info['fl_name']="|".$str.$info['fl_name'];
            }
            $result[] = $info;
            //把这个节点从数组中移除,减少后续递归消耗
            unset($data[$key]);
            //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
            $this->getChild($data,$info['id'],$level+1);
        }
    }
    return $result;
}

  }
?>